package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.bean.EmployeeBean;
import com.project.bean.MailBean;
import com.project.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

@RestController
@RequestMapping("mail")
public class MailController {
    @Autowired
    private IMailService service;

    @RequestMapping("cutByItem")
    public IPage<MailBean> cutByItem(Integer pageNO,
                                     String subject, LocalDate startDate,
                                     LocalDate endDate, HttpServletRequest req) {
        EmployeeBean em = (EmployeeBean) req.getSession().getAttribute("loginEm");

        IPage<MailBean> ip = service.cutByItem(pageNO, em.getEmId(), subject, startDate, endDate);
        return ip;
    }

    @RequestMapping("findById")
    public MailBean findById(Integer id) {
        return service.findById(id);
    }

    @RequestMapping("update")
    public String update(Integer id) {
        service.update(id);
        return "updateOK";
    }

    @RequestMapping("send")
    public String send(MailBean mail, HttpServletRequest req) {
        EmployeeBean em = (EmployeeBean) req.getSession().getAttribute("loginEm");
        mail.setSenderId(em.getEmId());
        HashMap<Integer, EmployeeBean> map = (HashMap<Integer, EmployeeBean>) req.getSession().getAttribute("emList");
        Set ketSet = map.keySet();
        Collection<EmployeeBean> emList = map.values();
        String str = "";
        for (EmployeeBean e : emList) {
            str += e.getName() + " ";
        }
        mail.setReceiver(str);
        service.send(mail, (Integer[]) ketSet.toArray(new Integer[ketSet.size()]));
        return "ok";
    }

}
